import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/my/add_key_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class KeyManagementPage extends StatefulWidget {
  const KeyManagementPage({super.key, this.isSelected = false, this.onConfirm});

  final bool isSelected;
  final Function? onConfirm;

  @override
  // ignore: library_private_types_in_public_api
  _KeyManagementPageState createState() => _KeyManagementPageState();
}

class _KeyManagementPageState extends State<KeyManagementPage>
    with SingleTickerProviderStateMixin {
  List<SecretKeyModel> _keys = [];
  int? selectedIndex;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadKeys();
    });
  }

  Future<void> _loadKeys() async {
    const url = '/get_keys';
    String token = SpUtil.getString('token') ?? '';

    var response = await DioHttp.of(context).get(url, null, token);
    var resString = json.decode(response.toString());

    if (resString['code'] == 200) {
      if (resString['data'] != null) {
        _keys = resString['data']
            .map<SecretKeyModel>((item) => SecretKeyModel.fromJson(item))
            .toList();
      } else {
        _keys = [];
      }
      setState(() {});
    }else{
      Fluttertoast.showToast(msg: resString['msg']);

    }
  }

  Future<void> _deleteKey(int index) async {
    const url = '/delete_key';
    String token = SpUtil.getString('token') ?? '';
    Map<String, dynamic> params = {'id': _keys[index].id};

    var response = await DioHttp.of(context).post(url, params, token);
    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      _loadKeys();
    }
  }

  void copyToClipboard(int index) {
    String text = _keys[index].key ?? '';
    Clipboard.setData(ClipboardData(text: text));
    Fluttertoast.showToast(msg: 'copy success'.t(context));
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Key Management'.t(context)),
        centerTitle: true,
        backgroundColor: themeProvider.mainColor,
        actions: widget.isSelected
            ? [
                TextButton(
                    onPressed: () {
                      if (selectedIndex != null) {
                        widget.onConfirm?.call(_keys[selectedIndex!]);
                        Navigator.pop(context);
                      } else {
                        Fluttertoast.showToast(
                            msg: 'Please select a key'.t(context));
                      }
                    },
                    child: Text('Confirm'.t(context)))
              ]
            : [],
      ),
      body: Column(
        children: [
          const SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const AddKeyPage()),
              ).then((_) => _loadKeys()); // 返回时刷新列表
            },
            child: Text('Add Key'.t(context)),
          ),
          const SizedBox(
            height: 10,
          ),
          const Divider(height: 1),
          Expanded(
            child: ListView.builder(
              itemCount: _keys.length,
              itemBuilder: (context, index) {
                final key = _keys[index];
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        if (widget.isSelected)
                          Checkbox(
                              value: selectedIndex == index,
                              onChanged: (value) {
                                setState(() {
                                  selectedIndex = index;
                                });
                              }),
                        Expanded(
                          child: Column(
                            children: [
                              ListTile(
                                title: Text('name: ${key.name ?? ''}'),
                                trailing: IconButton(
                                  icon: const Icon(Icons.delete),
                                  onPressed: () => _deleteKey(index),
                                ),
                              ),
                              ListTile(
                                title: Text('key: ${key.key ?? ''}'),
                                trailing: IconButton(
                                  icon: const Icon(Icons.copy),
                                  onPressed: () => copyToClipboard(index),
                                ),
                              ),
                              const Divider(
                                height: 1,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class SecretKeyModel {
  String? name;
  String? key;
  int? id;

  SecretKeyModel({
    this.name,
    this.key,
    this.id,
  });

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['name'] = name;
    map['key'] = key;
    map['id'] = id;

    return map;
  }

  factory SecretKeyModel.fromJson(Map<String, dynamic> json) => SecretKeyModel()
    ..name = json['name'] as String?
    ..id = json['id'] as int?
    ..key = json['key'] as String?;
}
